<template>
  <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
    <el-card shadow="hover" class="mb-[10px]">
      <el-form ref="formRef" :model="formModel" :inline="true" @submit.prevent="handleQuery">
        <el-form-item v-for="item in columns" v-bind:key="item.prop" :label="item.label" :prop="item.prop">
          <!-- 输入框 -->
          <el-input
            v-if="item.type === 'input'"
            v-model="formModel[item.prop]"
            :placeholder="item.placeholder || `请输入${item.label}`"
            clearable
            @keyup.enter="handleQuery"
          />
          <!-- 下拉选择器 -->
          <el-select v-if="item.type === 'select'" v-model="formModel[item.prop]" :placeholder="item.placeholder || `请选择${item.label}`" clearable>
            <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
          <!-- 日期选择器 -->
          <el-date-picker
            v-else-if="item.type === 'date'"
            v-model="formModel[item.prop]"
            type="date"
            :placeholder="item.placeholder || `请选择${item.label}`"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
          <!-- 日期范围 -->
          <el-date-picker
            v-else-if="item.type === 'dateRange'"
            v-model="formModel[item.prop]"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
          <!-- 数字输入框 -->
          <el-input-number
            v-else-if="item.type === 'number'"
            v-model="formModel[item.prop]"
            :placeholder="item.placeholder || `请输入${item.label}`"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item class="footer-button">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </transition>
</template>

<script setup name="NimbusSearch" lang="ts">
import { propTypes } from '@/utils/propTypes';

const formRef = ref<ElFormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
  float: propTypes.string.def('right'),
  columns: {
    type: Array as PropType<TableColumn[]>,
    required: true,
    default: () => []
  },
  modelValue: {
    type: Object,
    default: () => ({})
  },
  excludeFields: {
    type: Array,
    default: () => ['pageNum', 'pageSize']
  }
});

const formModel = reactive<any>({});
const emit = defineEmits(['update:modelValue', 'query']);

const initFormModel = () => {
  props.columns.forEach((column) => {
    if (props.excludeFields.includes(column.prop)) {
      return;
    }
    if (props.modelValue[column.prop] !== undefined) {
      formModel[column.prop] = props.modelValue[column.prop];
    } else {
      if (column.type === 'number') {
        formModel[column.prop] = null;
      } else if (column.type === 'dateRange') {
        formModel[column.prop] = [];
      } else {
        formModel[column.prop] = '';
      }
    }
  });
};

// 创建响应式表单模型
watch(() => props.columns, initFormModel, { immediate: true });
// 监听表单变化，同步到父组件
watch(
  formModel,
  (newValue) => {
    const syncValue = { ...props.modelValue };
    // 只更新非排除字段
    Object.keys(newValue).forEach((key) => {
      if (!props.excludeFields.includes(key)) {
        syncValue[key] = newValue[key];
      }
    });
    emit('update:modelValue', syncValue);
  },
  { deep: true }
);
// 监听父组件的 modelValue 变化，同步到表单
watch(
  () => props.modelValue,
  (newValue) => {
    Object.keys(newValue).forEach((key) => {
      if (!props.excludeFields.includes(key) && formModel[key] !== newValue[key]) {
        formModel[key] = newValue[key];
      }
    });
  },
  { deep: true }
);

onMounted(() => {
  props.columns.forEach((column) => {
    console.log('mounted: ' + column.label);
  });
});

onUnmounted(() => {
  console.log('unmounted');
});

// 查询方法
const handleQuery = () => {
  const queryParams = { ...props.modelValue, pageNum: 1 };
  // 过滤掉空值
  Object.keys(formModel).forEach((key) => {
    if (!props.excludeFields.includes(key)) {
      if (formModel[key] !== '' && formModel[key] !== null && formModel[key] !== undefined) {
        if (Array.isArray(formModel[key]) && formModel[key].length === 0) {
          return;
        }
        queryParams[key] = formModel[key];
      } else {
        // 确保空值也被传递，用于清除参数
        queryParams[key] = formModel[key];
      }
    }
  });
  emit('query', queryParams);
};

// 重置方法
const handleReset = () => {
  formRef.value?.resetFields();
  setTimeout(() => {
    handleQuery();
  }, 100);
};

// 暴露方法给父组件
defineExpose({
  formRef,
  handleQuery,
  handleReset
});
</script>

<style lang="scss" scoped>
.footer-button {
  float: v-bind(float);
}
</style>
